<template>
  <el-container class='elheight'>
    <el-aside class="appTree">
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData"
                       @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>小区名称：<el-input placeholder="请输入小区名称"
                        v-model="queryData.communityName"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>楼栋名称：<el-input placeholder="请输入楼栋名称"
                        v-model="queryData.buildingName"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>楼栋长名称：<el-input placeholder="请输入楼栋长名称"
                        v-model="queryData.buildingLeaderName"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>
              楼栋类型：
              <el-select v-model="queryData.buildingType" placeholder="请选择楼栋类型" filterable clearable>
                <el-option v-for="item in dictData.buildingType" :key="item.id" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick"
                         type="primary"
                         icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows"
                     v-on:checkSingleRow="checkSingleRow"
                     v-on:changeSingleRow="changeSingleRow"
                     v-on:deleSingleRow="deleSingleRow" />
          <el-dialog :title="dialogTitle"
                     :visible.sync="dialogFormVisible"
                     :before-close="close">
            <el-collapse v-model="activeNames">
              <el-collapse-item name="1" title='楼栋信息'>
                <el-form :model="formData"
                         :rules="rules"
                         ref="formData"
                         :disabled="showOnly"
                         label-width="120px"
                         size="mini">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="网格"
                                    prop="allGridIdArr">
                        <!-- <grid-cascader v-model="formData.allGridId"
                                       @changeGrid="handleGridCascader"></grid-cascader> -->
                        <div class="block">
                          <el-cascader placeholder="请选择"
                            :options="treeOption"
                            filterable
                            clearable
                            :props="gridIdProps"
                            v-model="formData.allGridIdArr"
                            @change="handleGridCascader">
                          </el-cascader>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="所属小区"
                                    prop="communityId">
                        <el-select filterable
                                   no-data-text="请选择"
                                   no-match-text="请选择"
                                   v-model="formData.communityId"
                                   placeholder="请选择所属小区"
                                   @change="handleChange">
                          <el-option v-for="(item, index) in communityData"
                                     :selected="index === 0"
                                     :key="item.id"
                                     :value="item.id"
                                     :label="item.name"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="楼栋地址"
                                    prop="addressDetail">
                        <el-input v-model="formData.addressDetail"
                                  readonly
                                  placeholder="请先选择网格和所属小区">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="楼栋类型"
                                    prop="buildingType">
                        <el-select filterable
                                   v-model="formData.buildingType"
                                   placeholder="请选择楼栋类型">
                          <el-option v-for="item in dictData.buildingType"
                                     :key="item.id"
                                     :value="item.code"
                                     :label="item.name"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="楼栋名称"
                                    prop="buildingName">
                        <el-input v-model="formData.buildingName"
                                  placeholder="请输入楼栋名称"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="建筑面积（²）"
                                    prop="buildingArea">
                        <el-input v-model="formData.buildingArea"
                                  placeholder="请输入建筑面积"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="楼栋长身份证号"
                                    prop="buildingLeaderIdentity">
                        <el-input v-model="formData.buildingLeaderIdentity"
                                  placeholder="请输入楼栋长身份证号"
                                  @blur="checkIdCard"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="楼栋长姓名"
                                    prop="buildingLeaderName">
                        <el-input v-model="formData.buildingLeaderName"
                                  placeholder="请输入楼长姓名"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="楼栋长手机号"
                                    prop="buildingLeaderPhone">
                        <el-input v-model="formData.buildingLeaderPhone"
                                  placeholder="请输入楼栋长手机号"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="选择经纬度"
                                prop="longitude">
                        <el-col :span="8">
                          <el-input v-model="formData.longitude"
                                    :disabled="true"
                                    placeholder="经度"></el-input>
                        </el-col>
                        <el-col :span="1"
                                style="text-align: center">-</el-col>
                        <el-col :span="7">
                          <el-input v-model="formData.latitude"
                                    :disabled="true"
                                    placeholder="纬度"></el-input>
                        </el-col>
                        <el-col :span="8">
                          <el-button type="text"
                                    @click="openSimpleMap">从地图选择</el-button>
                        </el-col>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="备注"
                                    style="width:100%"
                                    prop="remark">
                        <el-input v-model="formData.remark"
                                  type="textarea"
                                  :rows="3"
                                  placeholder="请输入备注"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="照片">
                        <app-upload ref="appUpload"
                                    v-model="formData.picture"></app-upload>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-collapse-item>
              <el-collapse-item name="2"
                                title="单元信息">
                <el-form :model="unitFormData"
                         :rules="rules"
                         ref="unitFormData"
                         :disabled="showOnly"
                         label-width="120px"
                         size="mini">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="楼层数"
                                    prop="floorNum">
                        <el-input v-model="unitFormData.floorNum"
                                  type="number"
                                  min="1"
                                  placeholder="请输入楼层数"
                                  ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="一梯几户"
                                    prop="laddersFamily">
                        <el-input v-model="unitFormData.laddersFamily"
                                  placeholder="请输入一梯几户"
                                  ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="单元长身份证号">
                        <el-input v-model="unitFormData.unitManagerIdentity"
                                  placeholder="请输入单元长身份证号"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="单元长姓名">
                        <el-input v-model="unitFormData.unitManagerName"
                                  placeholder="请输入单元长姓名"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="单元长手机号"
                                    prop="unitManagerPhone">
                        <el-input v-model="unitFormData.unitManagerPhone"
                                  placeholder="请输入单元长手机号"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="户数"
                                    prop="familyNum">
                        <el-input disabled=""
                                  v-model="formData.familyNum"
                                  type="number"
                                  min="1"
                                  placeholder="生成单元计算"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="操作">
                        <el-button @click="addUnit">添加单元</el-button>
                        <el-button :disabled="showPart"
                                   @click="delUnit">删除单元</el-button>
                        <el-button @click="previewUnit">预览单元</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
                <el-table :data="unitTableData"
                          header-row-class-name="unitTablleName"
                          @row-click="handleUnitTableClickEvent">
                  <el-table-column v-for="(item, index) in unitTableColumns"
                                   :key="index"
                                   :prop="item.prop"
                                   :label="item.label">
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
            <div v-if="!showOnly"
                 slot="footer"
                 class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary"
                         @click="save('formData')">提 交</el-button>
            </div>
          </el-dialog>
          <el-dialog class="dialog-body-mini"
                     :visible.sync="showMap"
                     title="楼栋标记"
                     width="70%"
                     top="8vh"
                     :before-close="mapCancel">
            <edit-map v-if="showMap"
                      :mode="mapMode"
                      @appMapCallback="appMapCallback"
                      :target="mapTarget"
                      :row-id="currentSelectedRowId"></edit-map>
          </el-dialog>
          <el-dialog class="dialog-body-mini"
                     :visible.sync="showPreview"
                     title="楼栋预览"
                     width="70%"
                     height="400"
                     top="8vh"
                     custom-class="previewClass"
                     @opened="previewOpen"
                     @close="closeCanvas"
                     center>
            <canvas id="canvasId"
                    width="1000"
                    height="300"></canvas>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import EditMap from '@/components/EditMap'
import GridCascader from '@/components/GridCascader'
import AppUpload from '@/components/AppUpload'
import { getCaseAllGridIdByGridTreeData, isCommonDo } from '@/utils/CommonUtil'
import { findBuilding, updateBuilding, deleteBuilding, createBuilding, findCommunityList, findUnitList } from '@/http/FangWuGuanLiApi'
import { createMapLocation, updateMapLocation } from '@/http/AppApi'
import { getUserGridTree } from '@/utils/SessionDataUtil'
import DictDataUtil from '@/utils/DictDataUtil'
import CanvasUtils from '@/utils/canvasUtils'
import { validateIdefer } from '@/utils/validate'
import { getPopulation } from '@/http/PopulationApi'
import { getAllRegion, getAllRegionObj } from '@/utils/region'
export default {
  data () {
    return {
      tableData: [],
      pageData: {},
      url: '',
      currentSelectedRowId: '',
      formData: {
        allGridId: '',
        communityId: '',
        buildingType: '',
        buildingName: '',
        familyNum: '',
        floorNum: '',
        laddersFamily: '',
        buildingLeaderName: '',
        buildingLeaderIdentity: '',
        buildingLeaderPhone: '',
        politicalStatus: ''
      },
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      treeOption: [],
      queryData: {},
      treeData: [],
      address: {
        address: '',
        area: '',
        temp1: '',
        temp2: '',
        temp3: ''
      },
      createCanvas: null,
      dialogTitle: '',
      dialogFormVisible: false,
      currentSelectedData: [],
      showOnly: false,
      showPart: false,
      showMap: false,
      showPreview: false,
      mapTarget: {},
      mapHackReset: false,
      mapMode: 'full',
      communityData: [],
      dictData: {},
      tableColumns: [
        { label: '楼栋名称', prop: 'buildingName' },
        { label: '小区名称', prop: 'communityName' },
        { label: '单元数', prop: 'unitNum' },
        { label: '户数', prop: 'familyNum' },
        { label: '楼栋长', prop: 'buildingLeaderName' },
        { label: '地图标注', prop: 'mapMarkStatus' }
      ],
      activeNames: ['1', '2'],
      unitTableData: [],
      unitFormData: {},
      unitTableColumns: [
        { label: '单元名', prop: 'unitName' },
        { label: '单元长身份证号', prop: 'unitManagerIdentity' },
        { label: '单元长联系方式', prop: 'unitManagerPhone' },
        { label: '单元长名字', prop: 'unitManagerName' },
        { label: '层数', prop: 'floorNum' },
        { label: '一梯几户', prop: 'laddersFamily' }
      ],
      rules: {
        allGridIdArr: [{
          required: true,
          message: '选择网格',
          trigger: 'blur'
        }],
        communityId: [{
          required: true,
          message: '请选择所属小区',
          trigger: 'blur'
        }],
        buildingType: [{
          required: true,
          message: '请选择楼栋类型',
          trigger: 'blur'
        }],
        buildingName: [{
          required: true,
          message: '请输入楼栋名称',
          trigger: 'blur'
        }],
        floorNum: [{
          required: true,
          message: '请输入楼层数',
          trigger: 'blur'
        }],
        longitude: [{
          required: true,
          message: '请填写经纬度',
          trigger: 'blur'
        }],
        latitude: [{
          required: true,
          message: '请填写经纬度',
          trigger: 'blur'
        }],
        laddersFamily: [{
          required: true,
          message: '请输入一梯几户',
          trigger: 'blur'
        }],
        buildingArea: [{
          required: true,
          message: '请输入楼栋面积',
          trigger: 'blur'
        }],
        buildingLeaderName: [{
          required: false,
          message: '请输入楼长姓名',
          trigger: 'blur'
        }],
        buildingLeaderIdentity: [{
          required: false,
          validator: function validatePhoneIdentity (rule, value, callback) {
            validateIdefer(rule, value, callback, 1)
          },
          message: '请输入身份证号',
          trigger: 'blur'
        }],
        buildingLeaderPhone: [{
          required: false,
          validator: function validatePhone (rule, value, callback) {
            let phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
            if (value) {
              setTimeout(() => {
                if (!phoneReg.test(value)) {
                  callback(new Error('手机格式有误'))
                } else {
                  callback()
                  return true
                }
              }, 1000)
            } else {
              callback()
              return true
            }
          },
          message: '请输入手机号',
          trigger: 'blur'
        }],
        unitManagerPhone: [{
          validator: function validatePhone (rule, value, callback) {
            let phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
            if (value) {
              setTimeout(() => {
                if (!phoneReg.test(value)) {
                  callback(new Error('手机格式有误'))
                } else {
                  callback()
                  return true
                }
              }, 1000)
            } else {
              callback()
              return true
            }
          },
          message: '请输入手机号',
          trigger: 'blur'
        }],
        unitManagerIdentity: [{
          validator: function validatePhoneIdentity (rule, value, callback) {
            validateIdefer(rule, value, callback, 1)
          },
          message: '请输入身份证',
          trigger: 'blur'
        }]
      }
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    GridCascader,
    AppUpload,
    EditMap
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
    this.getDictData()
  },
  methods: {
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.formData.familyNum) {
            this.$message({
              type: 'warning',
              message: '户数不能空'
            })
            return false
          }
          this.$refs['unitFormData'].validate((valid) => {
            if (valid) {
              this.dialogFormVisible = false
              if (this.formData) {
                if (!this.beforeSubmit()) {
                  return
                }
              }
              if (this.formData.id) {
                updateBuilding(this.formData).then(resp => {
                  if (resp.code && resp.code === '200') {
                    this.getTableData()
                    this.cancel(formName)
                    this.$message({
                      type: 'success',
                      message: '修改成功'
                    })
                  }
                })
              } else {
                createBuilding(this.formData).then(resp => {
                  if (resp.code && resp.code === '200') {
                    this.getTableData()
                    this.cancel(formName)
                    this.dialogFormVisible = false
                    this.$refs[formName].resetFields()
                    this.$message({
                      type: 'success',
                      message: '添加成功'
                    })
                  }
                })
              }
            }
          })
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteBuilding(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel (formName) {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.unitFormData = {}
      this.unitTableData = []
      this.communityData = []
      this.$refs[formName].resetFields()
    },
    close () {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.unitFormData = {}
      this.unitTableData = []
      this.communityData = []
      this.$refs['formData'].resetFields()
    },
    getTableData () {
      let param = this.queryData
      findBuilding(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            isCommonDo(this.pageData, this)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getTreeData () {
      let gridTree = getUserGridTree()
      if (gridTree && gridTree instanceof Array) {
        this.treeData = gridTree
        this.treeOption = gridTree
      }
    },
    beforeSubmit () {
      this.formData.unitList = this.unitTableData
      if (this.formData.allGridIdArr && this.formData.allGridIdArr.length !== 0) {
        let liveIndex = this.formData.allGridIdArr.length - 1
        let liveData = {}
        liveData.id = this.formData.allGridIdArr[liveIndex]
        liveData.items = this.treeData
        liveData.isGetAllId = true
        this.formData.allGridId = getAllRegion(liveData)
      } else {
        this.formData.allGridId = ''
      }
      return true
    },
    getCommunityData (gridId, flag) {
      if (gridId && gridId !== '') {
        let param = { likeAllGridId: gridId }
        findCommunityList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data && data instanceof Array) {
              this.communityData = data
              if (this.communityData.length === 0) {
                this.formData.communityId = ''
                this.address.area = ''
              }
              if (flag === 1) {
                this.handleChange(this.formData.communityId)
              }
            }
          }
        })
      }
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.likeAllGridId = data.id
      this.getTableData()
      this.formData.allGridId = getCaseAllGridIdByGridTreeData(data)
      this.formData.allGridIdArr = this.formData.allGridId.split(',')
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else if (callbackData.btnType === 'draw') {
        let rowData = callbackData.rows[0]
        if (!rowData) {
          this.$message({
            type: 'info',
            message: '请选择数据'
          })
          return
        }
        this.mapMode = 'full'
        this.mapHackReset = true
        this.showMap = true
        let target = {}
        target.targetId = rowData.id
        target.targetType = 'building'
        this.mapTarget = target
      } else {
        this.showOnly = callbackData.sohwOnly
        this.showPart = callbackData.showPart
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
        if (callbackData.btnType === 'post') {
          this.formData = this.formData.allGridId ? this.formData : {}
          // this.addUnit()
        } else {
          let tempData = {}
          tempData = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(tempData)
          this.getUnit(this.formData.id)
        }
      }
    },
    checkSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    changeSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    deleSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      }
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        if (appMapInfo.target.targetId) {
          let mapLocation = {}
          if (appMapInfo.poly && appMapInfo.poly instanceof Array && appMapInfo.poly.length > 0) {
            let length = appMapInfo.poly.length
            this.saveMapLocationInfoByArray(0, length, appMapInfo)
          } else {
            mapLocation = this.appMapInfo2MapLocation(appMapInfo)
            this.saveMapLocationInfo(mapLocation)
          }
        } else {
          this.showOnly = false
          this.showMap = false
          this.$set(this.formData, 'latitude', appMapInfo.lnglat.lat)
          this.$set(this.formData, 'longitude', appMapInfo.lnglat.lng)
        }
      }
      return ''
    },
    appMapInfo2MapLocation (appMapInfo) {
      let mapLocation = {}
      mapLocation.targetId = appMapInfo.target.targetId
      mapLocation.targetType = appMapInfo.target.targetType

      if (!appMapInfo.poly) {
        mapLocation.mapArea = appMapInfo.polyPathArr
        mapLocation.mapColor = appMapInfo.polyColor
        // 地图信息id存在则不允许修改targetId和targetType
        if (appMapInfo.id) {
          mapLocation.id = appMapInfo.id
          delete mapLocation.targetId
          delete mapLocation.targetType
        }
      }
      if (appMapInfo.clearStatus) {
        mapLocation.clearStatus = appMapInfo.clearStatus
      }
      if (appMapInfo.markPosition) {
        mapLocation.longitude = appMapInfo.markPosition.lng
        mapLocation.latitude = appMapInfo.markPosition.lat
      }
      return mapLocation
    },
    saveMapLocationInfoByArray (i, length, appMapInfo) {
      if (i >= length) {
        return
      }
      let mapLocation = {}
      mapLocation = this.appMapInfo2MapLocation(appMapInfo)
      mapLocation.mapArea = appMapInfo.poly[i].polyPathArr
      mapLocation.mapColor = appMapInfo.poly[i].polyColor
      mapLocation.id = appMapInfo.poly[i].id
      if (mapLocation.id) {
        delete mapLocation.targetId
        delete mapLocation.targetType
      }
      i++
      let data = mapLocation
      console.log('maplocation id = ' + mapLocation.id)
      if (mapLocation.id) {
        updateMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      }
    },
    saveMapLocationInfo (mapLocation) {
      if (mapLocation.id) {
        updateMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
          }
        })
      }
      this.mapCancel()
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    handleGetCommunityData (allGridId) {
      if (allGridId && allGridId instanceof Array && allGridId.length > 0) {
        let gridId = allGridId[allGridId.length - 1]
        this.getCommunityData(gridId)
      }
    },
    getDictData () {
      this.dictData.buildingType = DictDataUtil.getBuildingType()
    },
    handleGridCascader (data) {
      if (data) {
        this.communityData = []
        let arr = data
        let regionData = {}
        regionData.id = arr[arr.length - 1]
        regionData.items = this.treeData
        let temp = getAllRegionObj(regionData)
        this.address.address = ''
        for (let i = 0; i < temp.length; i++) {
          const element = temp[i]
          this.address.address += element.name + ' '
        }
        this.$set(this.formData, 'addressDetail', this.address.address + this.address.area)
        this.handleGetCommunityData(arr)
      }
    },
    buildUnitName () {
      if (this.unitTableData && this.unitTableData instanceof Array) {
        let unitSize = this.unitTableData.length
        let unitName = (unitSize + 1) + '单元'
        return unitName
      }
    },
    addUnit () {
      let unitFormData = {}
      let floorNum = this.unitFormData.floorNum
      let laddersFamily = this.unitFormData.laddersFamily
      if (floorNum && laddersFamily) {
        if (this.unitTableData && this.unitTableData instanceof Array) {
          unitFormData.unitName = this.buildUnitName()
          unitFormData.floorNum = floorNum
          unitFormData.unitManagerIdentity = this.unitFormData.unitManagerIdentity
          unitFormData.unitManagerPhone = this.unitFormData.unitManagerPhone
          unitFormData.unitManagerName = this.unitFormData.unitManagerName
          unitFormData.laddersFamily = laddersFamily
          this.unitTableData.push(unitFormData)
          unitFormData = {}
          let familyNum = 0
          for (let i = 0; i < this.unitTableData.length; i++) {
            familyNum += parseInt(this.unitTableData[i].floorNum * this.unitTableData[i].laddersFamily)
          }
          this.$set(this.formData, 'familyNum', familyNum)
          this.unitFormData = this.unitTableData[this.unitTableData.length - 1]
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请选择单元楼层和每层户数'
        })
      }
    },
    delUnit () {
      if (this.unitTableData && this.unitTableData instanceof Array) {
        if (this.unitFormData) {
          let index = this.unitTableData.length - 1
          this.unitTableData.splice(index, 1)
          let familyNum = 0
          for (let i = 0; i < this.unitTableData.length; i++) {
            familyNum += parseInt(this.unitTableData[i].floorNum * this.unitTableData[i].laddersFamily)
          }
          this.$set(this.formData, 'familyNum', familyNum)
          // this.unitTableData.forEach((value, index, arr) => {
          //   if (this.unitFormData.unitName === value.unitName) {
          //     this.unitTableData.splice(index, 1)
          //   }
          // })
        } else {
          this.$message({
            type: 'info',
            message: '请选择数据'
          })
        }
      }
    },
    getUnit (buildingId) {
      if (buildingId) {
        let param = { buildingId: buildingId }
        findUnitList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data && data instanceof Array) {
              this.unitTableData = data.reverse()
              if (data.length !== 0) {
                this.unitFormData = this.unitTableData[0]
              }
              this.getCommunityData(this.formData.gridId, 1)
              let regionData = {}
              regionData.id = this.formData.gridId
              regionData.items = this.treeData
              let gridIdArr = getAllRegion(regionData)
              let gridIdNameList = getAllRegionObj(regionData)
              this.$set(this.formData, 'allGridIdArr', gridIdArr)
              this.address.address = this.buildAddressByGrid(gridIdNameList)
              this.$set(this.formData, 'addressDetail', this.address.address + this.address.area)
            }
          }
        })
      }
    },
    buildAddressByGrid (gridIdNameList) {
      let address = ''
      if (gridIdNameList && gridIdNameList.length > 0) {
        for (let i = 0; i < gridIdNameList.length; i++) {
          const g = gridIdNameList[i]
          address += g.name + ''
        }
      }
      return address
    },
    previewUnit () {
      let floorNum = this.unitFormData.floorNum
      let unitNum = this.unitTableData.length
      let familyNum = this.unitFormData.laddersFamily
      if (floorNum && unitNum && familyNum) {
        this.showPreview = true
      } else {
        this.$message({
          type: 'warning',
          message: '请先填写楼栋信息'
        })
      }
    },
    previewOpen () {
      let unitNum = this.unitTableData.length
      let canvasEl = document.getElementById('canvasId')
      let oldladdersFamily1 = 0
      this.createCanvas = new CanvasUtils(canvasEl, 100, 50, 100, 0, unitNum, this.maxFloorNum(), this.totalFamilyNum())
      for (let k = 0; k < unitNum; k++) {
        let laddersFamily = parseInt(this.unitTableData[k].laddersFamily)
        let floorNum = parseInt(this.unitTableData[k].floorNum)
        if (k > 0) {
          oldladdersFamily1 += parseInt(this.unitTableData[k - 1].laddersFamily)
        } else {
          oldladdersFamily1 = 0
        }
        this.createCanvas.drawTitle(k, 100 * (oldladdersFamily1 + k) + (100 * laddersFamily) / 2)
        for (let i = 0; i < laddersFamily; i++) {
          for (let j = 0; j < floorNum; j++) {
            this.createCanvas.drawRect(100 * i, j * 50, 100, 50, 100 * (oldladdersFamily1 + k), 80)
          }
        }
      }
      let oldladdersFamily2 = 0
      for (let k = 0; k < unitNum; k++) {
        let laddersFamily = parseInt(this.unitTableData[k].laddersFamily)
        let floorNum = parseInt(this.unitTableData[k].floorNum)
        if (k > 0) {
          oldladdersFamily2 += parseInt(this.unitTableData[k - 1].laddersFamily)
        } else {
          oldladdersFamily2 = 0
        }
        for (let i = 0; i < laddersFamily; i++) {
          for (let j = 0, u = floorNum; j < floorNum; j++, u--) {
            if (i === 0) {
              this.createCanvas.drawUnite(((50 * i) + 50) + (oldladdersFamily2 + k) * 100, (j * 50) + 105, u, i + 1)
            } else {
              this.createCanvas.drawUnite(((100 * i) + 50) + (oldladdersFamily2 + k) * 100, (j * 50) + 105, u, i + 1)
            }
          }
        }
      }
    },
    maxFloorNum: function () {
      let maxN = parseInt(this.unitTableData[0].floorNum)
      for (let i = 0; i < this.unitTableData.length; i++) {
        let curMax = parseInt(this.unitTableData[i].floorNum)
        if (curMax > maxN) {
          maxN = curMax
        }
      }
      return maxN
    },
    totalFamilyNum () {
      let familyNum = 0
      for (let i = 0; i < this.unitTableData.length; i++) {
        familyNum += parseInt(this.unitTableData[i].laddersFamily)
      }
      return familyNum
    },
    closeCanvas () {
      this.createCanvas.clearCanvas()
    },
    handleUnitTableClickEvent (row, column, event) {
      this.unitFormData = row
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    },
    handleChange (id) {
      this.communityData.find((item) => {
        if (item.id === id) {
          this.address.area = item.name
          this.$set(this.formData, 'addressDetail', this.address.address + this.address.area)
        }
      })
    },
    checkIdCard (event) {
      let value = event.srcElement.value
      getPopulation(value).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.$set(this.formData, 'buildingLeaderName', data.name)
          this.$set(this.formData, 'buildingLeaderPhone', data.phone)
        }
      })
    }
  },
  computed: {},
  watch: {}
}
</script>
<style scoped>
.el-main >>> .previewClass .el-dialog__body {
  overflow: auto;
  height: 700px;
}
.el-main >>> .previewClass .el-dialog__header {
  padding: 20px;
  background: #409eff;
}
.el-form >>> .el-form-item__error {
  margin-top: 2px;
}
.el-table >>> .unitTablleName th {
  color: #fff;
}
.el-form >>> .el-input__inner {
  height: 37px;
}
.el-form >>> .el-form-item__label {
  line-height: 37px;
}
.el-form >>> .el-cascader__label {
  line-height: 37px;
}
.el-table >>> .unitTablleName th .cell {
  white-space: nowrap;
  font-weight: normal;
}
</style>
